package es.xpt.ysf.utils;

import java.io.InputStream;
import java.sql.SQLException;

import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.XmlDataSet;
import org.dbunit.ext.mysql.MySqlConnection;
import org.dbunit.operation.DatabaseOperation;

import es.xpt.ysf.jaas.YSFPrincipal;

public class DBUnitUtils { // NO_UCD
	private static YSFPrincipal principal = null;
	private static String[] xmlDB;
	private static IDatabaseConnection conn=null;
	private static java.sql.Connection connection=null;
	
	public synchronized static IDatabaseConnection getConnection() throws Exception {
		if (conn==null)
			conn = new MySqlConnection(connect(), "");
		return conn;
	}

	public static IDataSet getDataSet(int i) throws Exception {	
		InputStream xmlStream = DBUnitUtils.class.getResourceAsStream(xmlDB[i]);		 
		IDataSet dataset = new XmlDataSet(xmlStream);
		return dataset;
	}


	
	public static java.sql.Connection connect()
			throws InstantiationException, IllegalAccessException,
			ClassNotFoundException, SQLException {

		return connection;
	}

	public static void setUpBeforeClass() throws Exception {		
		for(int i=0; i<=xmlDB.length-1; i++){
			DatabaseOperation.CLEAN_INSERT.execute(getConnection(), getDataSet(i));
		}
	}

	public static void tearDownAfterClass() throws Exception {
		for(int i=xmlDB.length-1; i>=0; i--){
			DatabaseOperation.DELETE_ALL.execute(getConnection(), getDataSet(i));
		}
	}

	/**
	 * @return the principal
	 */
	public static YSFPrincipal getPrincipal() {
		return principal;
	}

	/**
	 * @param principal the principal to set
	 */
	public static void setPrincipal(YSFPrincipal principalParam) {
		principal = principalParam;
	}

	/**
	 * @return the xmlDB
	 */
	public static String[] getXmlDB() {
		return xmlDB;
	}

	/**
	 * @param xmlDB the xmlDB to set
	 */
	public static void setXmlDB(String[] xmlDB) {
		DBUnitUtils.xmlDB = xmlDB;
	}

	/**
	 * @return the conn
	 */
	public static IDatabaseConnection getConn() {
		return conn;
	}

	/**
	 * @param conn the conn to set
	 */
	public static void setConn(IDatabaseConnection conne) {
		conn = conne;
	}

	/**
	 * @param connection the connection to set
	 */
	public static void setConnection(java.sql.Connection connection) {
		DBUnitUtils.connection = connection;
	}

}
